package com.hznu.coursemanagerbackend.modules.sys.service.base;


import com.hznu.coursemanagerbackend.modules.sys.entity.User;
import com.hznu.coursemanagerbackend.shiro.RetryLimitHashedCredentialsMatcher;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.subject.Subject;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 基础服务
 */
public class BaseService {
    protected Logger log = LogManager.getLogger(getClass());

    public ModelAndView view = new ModelAndView();

    //用户登录处理(待解决)
    public boolean userLogin(Subject subject, HttpServletRequest request, String username, String password) //session
    {
        if ("get".equalsIgnoreCase(request.getMethod())) {
            return false;
        }

        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            return false;
        }

        UsernamePasswordToken token = new UsernamePasswordToken(username, password);

        try {
            subject.login(token);
            return true;
        } catch (ExcessiveAttemptsException e) {
//            message.setCode(AppConstant.USERNAME_NOTEXIST);
//            message.setMsg("帐号被锁定10分钟");
            Cache<String, AtomicInteger> cache = RetryLimitHashedCredentialsMatcher.getPasswordRetryCache();
            if (null == cache.get(username + "locked")) {
                cache.put(username + "locked", new AtomicInteger(0));
            }
            e.printStackTrace();
            return false;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {

        }
    }


    //过滤敏感信息
    public void filterSensitiveInfo(User user) {
//        user.setUsername(null);
        user.setPassword(null);
        user.setSalt(null);
    }
}
